package cn.iocoder.yudao.module.erp.service.stock;

import cn.hutool.core.collection.CollUtil;
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.erp.controller.admin.stock.vo.warehouse.ErpWarehouseListReqVO;
import cn.iocoder.yudao.module.erp.controller.admin.stock.vo.warehouse.ErpWarehouseSaveReqVO;
import cn.iocoder.yudao.module.erp.dal.dataobject.product.ErpProductCategoryDO;
import cn.iocoder.yudao.module.erp.dal.dataobject.stock.ErpWarehouseDO;
import cn.iocoder.yudao.module.erp.dal.mysql.stock.ErpWarehouseMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.*;
import static cn.iocoder.yudao.module.erp.enums.ErrorCodeConstants.PRODUCT_CATEGORY_PARENT_IS_CHILD;

/**
 * ERP 仓库 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class ErpWarehouseServiceImpl implements ErpWarehouseService {

    @Resource
    private ErpWarehouseMapper warehouseMapper;

    @Override
    public Long createWarehouse(ErpWarehouseSaveReqVO createReqVO) {
        // 插入
        validateParent(null, createReqVO.getParentId());
        ErpWarehouseDO warehouse = BeanUtils.toBean(createReqVO, ErpWarehouseDO.class);
        //如果仓库名称重复，则报错
        Long count = warehouseMapper.selectCount(
                new QueryWrapper<ErpWarehouseDO>()
                        .eq("name", createReqVO.getName())
        );
        if (count > 0) {
            throw new ServiceException("仓库名称不能重复");
        }

        warehouseMapper.insert(warehouse);
        // 返回
        return warehouse.getId();
    }

    @Override
    public void updateWarehouse(ErpWarehouseSaveReqVO updateReqVO) {
        // 校验存在
        validateWarehouseExists(updateReqVO.getId());
        validateParent(updateReqVO.getId(), updateReqVO.getParentId());
        // 更新
        ErpWarehouseDO updateObj = BeanUtils.toBean(updateReqVO, ErpWarehouseDO.class);
        warehouseMapper.updateById(updateObj);
    }


    private void validateParent(Long id, Long parentId) {
        if (parentId == null || parentId.equals(ErpWarehouseDO.PARENT_ID_ROOT)) {
            return;
        }
        // 1. 不能设置自己为父产品分类
        if (Objects.equals(id, parentId)) {
            throw exception(WAREHOUSE_PARENT_ERROR);
        }
        // 2. 父产品分类不存在
        ErpWarehouseDO erpWarehouseDO = warehouseMapper.selectById(parentId);
        if (erpWarehouseDO == null) {
            throw exception(WAREHOUSE_PARENT_NOT_EXISTS);
        }
        if (erpWarehouseDO.getParentId() != null && !ErpWarehouseDO.PARENT_ID_ROOT.equals(erpWarehouseDO.getParentId())) {
            throw exception(WAREHOUSE_LEVEL_EXCEED);
        }
        // 3. 递归校验父产品分类，如果父产品分类是自己的子产品分类，则报错，避免形成环路
        if (id == null) { // id 为空，说明新增，不需要考虑环路
            return;
        }
        for (int i = 0; i < Short.MAX_VALUE; i++) {
            // 3.1 校验环路
            parentId = erpWarehouseDO.getParentId();
            if (Objects.equals(id, parentId)) {
                throw exception(WAREHOUSE_PARENT_IS_CHILD);
            }
            // 3.2 继续递归下一级父产品分类
            if (parentId == null || ErpWarehouseDO.PARENT_ID_ROOT.equals(parentId)) {
                break;
            }
            erpWarehouseDO = warehouseMapper.selectById(parentId);
            if (erpWarehouseDO == null) {
                break;
            }
        }
    }


    @Override
    public void deleteWarehouse(Long id) {
        // 校验存在
        validateWarehouseExists(id);
        // 删除
        warehouseMapper.deleteById(id);
    }

    private void validateWarehouseExists(Long id) {
        if (warehouseMapper.selectById(id) == null) {
            throw exception(WAREHOUSE_NOT_EXISTS);
        }
    }

    @Override
    public ErpWarehouseDO getWarehouse(Long id) {
        return warehouseMapper.selectById(id);
    }

    @Override
    public List<ErpWarehouseDO> validWarehouseList(Collection<Long> ids) {
        if (CollUtil.isEmpty(ids)) {
            return Collections.emptyList();
        }
        List<ErpWarehouseDO> list = warehouseMapper.selectBatchIds(ids);
        Map<Long, ErpWarehouseDO> warehouseMap = convertMap(list, ErpWarehouseDO::getId);
        for (Long id : ids) {
            ErpWarehouseDO warehouse = warehouseMap.get(id);
            if (warehouseMap.get(id) == null) {
                throw exception(WAREHOUSE_NOT_EXISTS);
            }
            if (CommonStatusEnum.isDisable(warehouse.getStatus())) {
                throw exception(WAREHOUSE_NOT_ENABLE, warehouse.getName());
            }
        }
        return list;
    }

    @Override
    public List<ErpWarehouseDO> getWarehouseListByStatus(Integer status) {
        return warehouseMapper.selectListByStatus(status);
    }

    @Override
    public List<ErpWarehouseDO> getWarehouseList(Collection<Long> ids) {
        return warehouseMapper.selectBatchIds(ids);
    }

    @Override
    public List<ErpWarehouseDO> getWarehouseList(ErpWarehouseListReqVO listReqVO) {
        return warehouseMapper.selectList(listReqVO);
    }

}
